package com.highcom.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.highcom.domain.Book;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

@Controller
public class AccountController {

    //使用HttpServletResponse相应对象
    @RequestMapping("/showData1")
    public void showData1(HttpServletResponse response) throws IOException {
        response.getWriter().write("message");
    }
    //使用 @ResponseBody 将返回的结果作为相应内容，而非响应的页面名称
    @RequestMapping("/showData2")
    @ResponseBody
    public String showData2()  {
        //return "page";
        return "{'name': 'Jack'}";
    }
    // 使用jackson将 对象 转化成  json
    @RequestMapping("/showData3")
    @ResponseBody
    public String showData3() throws JsonProcessingException {
        Book book = new Book();
        book.setName("Springmvc");
        book.setPrice(66.6D);

        ObjectMapper om = new ObjectMapper();
        return om.writeValueAsString(book);
    }
    //使用springmvc 注解驱动，对标注@ResponseBody的注解控制器方法进行结果转换；
    //自动调用jackson提供的类型转换；
    //在配置文件中开启 <mvc:annotation-driven/>
    @RequestMapping("/showData4")
    @ResponseBody
    public Book showData4(){
        Book book = new Book();
        book.setName("Springmvc");
        book.setPrice(66.6D);
        return book;
    }

    @RequestMapping("/showData5")
    @ResponseBody
    public ArrayList<Book> showData5(){
        Book book1 = new Book();
        book1.setName("Springmvc");
        book1.setPrice(66.6D);

        Book book2 = new Book();
        book2.setName("Springmvc2");
        book2.setPrice(62.6D);
        ArrayList<Book> a1 = new ArrayList<>();
        a1.add(book1);
        a1.add(book2);
        return a1;
    }
}
